const { Client } = require('pg');
const turf = require('@turf/turf');
const fs = require('fs');

// 读取 GeoJSON 文件
const geojson = JSON.parse(fs.readFileSync('data_1000hpa_2018-11-01.geojson', 'utf8'));

// 创建 PostgreSQL 客户端
const client = new Client({
    host: "127.0.0.1",
	user: "postgres",
	password: "whuyiyulu666666",
    //此处是你添加的数据库名
	database: "animalsmigration",
	// multipleStatements: true,
	port : 5432,
});

async function insertData() {
  try {
    await client.connect();

    // 插入元数据
    const timestamp = geojson.name.split('_')[2]; // 假设文件名格式为 data_YYYY-MM-DD
    const pressureLevel = parseInt(geojson.name.split('_')[1].split('hpa')[0]);

    await client.query(
      'INSERT INTO climate_metadata (timestamp, pressure_level) VALUES ($1, $2) ON CONFLICT (timestamp, pressure_level) DO NOTHING',
      [timestamp, pressureLevel]
    );

    // 批量插入空间数据
    const insertQuery = `
      INSERT INTO climate_polygons (timestamp, pressure_level, temperature, humidity, u_wind, v_wind, geom)
      VALUES ($1, $2, $3, $4, $5, $6, ST_SetSRID(ST_GeomFromGeoJSON($7), 4326))
    `;

    const values = geojson.features.map((feature) => [
      timestamp,
      pressureLevel,
      feature.properties.temperature,
      feature.properties.humidity,
      feature.properties.u_wind,
      feature.properties.v_wind,
      JSON.stringify(feature.geometry),
    ]);

    for (const value of values) {
      await client.query(insertQuery, value);
    }

    console.log('数据成功插入！');
  } catch (err) {
    console.error('插入数据时出错：', err);
  } finally {
    await client.end();
  }
}

insertData();


